package com.cfjjc.gz.common.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.commons.io.IOUtils;
import com.cfjjc.gz.common.exception.OTSException;

/**
 * 文件操作实用类
 */
public class FileUtil {

	/**
	 * 重命名文件
	 * 
	 * @param fileNames 文件名称数组
	 * @param files 文件
	 * @return 结果文件数组
	 */
	public static File[] renameToFiles(String[] fileNames, File[] files) {
		File[] retFiles = null;
		if (fileNames != null && fileNames.length > 0) {
			retFiles = new File[fileNames.length];

			for (int i = 0, n = fileNames.length; i < n; i++) {
				File dist = new File(fileNames[i]);
				files[i].renameTo(dist);
				retFiles[i] = dist;
			}
		}
		return retFiles;
	}

	/**
	 * save文件
	 * 
	 * @param file
	 * @param fileName
	 * @param filePath
	 * @return
	 * @throws Exception
	 */
	public static long saveFile(File file, String fileName, String filePath) throws Exception {
		if (file == null) {
			return 0;
		}

		File filepath = new File(filePath);
		if (!filepath.isDirectory())
			filepath.mkdirs();
		File filedesc = new File(filepath, fileName);

		return copyFile(file, filedesc);
	}

	/**
	 * copy文件
	 * 
	 * @param fromFile 源文件
	 * @param toFile 目标文件
	 * @return
	 */
	public static long copyFile(File fromFile, File toFile) throws OTSException {
		long len = 0;

		InputStream in = null;
		OutputStream out = null;
		try {
			in = new FileInputStream(fromFile);
			out = new FileOutputStream(toFile);
			byte[] t = new byte[1024];
			int ii = 0;
			while ((ii = in.read(t)) > 0) {
				out.write(t, 0, ii);
				len += ii;
			}

		} catch (IOException e) {
			e.printStackTrace();
			throw new OTSException(e);

		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			if (out != null) {
				try {
					out.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

		}

		return len;
	}

	/**
	 * 验证文件正确性
	 * 
	 * @param file 待验证文件
	 * @param exts 允许的类型后缀数组
	 * @return
	 * @throws Exception
	 */
	public static boolean verifyFile(File file, String[] exts) throws Exception {
		boolean flag = false;
		if (file != null) {
			String ext = getExtension(file.getName());
			if (ext == null) {
				return false;
			}
			if (exts != null && exts.length > 0) {

				if (exts[0].equals("*.*"))
					return true;
				for (int i = 0; i < exts.length; i++) {

					if (ext.equalsIgnoreCase(exts[i])) {
						flag = true;
						break;
					}
				}
			}
		}

		return flag;

	}

	/**
	 * 取得文件扩展名
	 * 
	 * @param fileName 文件全名
	 * @return
	 */
	public static String getExtension(String fileName) {

		int newEnd = fileName.length();
		int i = fileName.lastIndexOf(".", newEnd);
		if (i != -1) {
			return fileName.substring(i + 1, newEnd);
		} else {
			return null;
		}
	}

    /**
     * Opens a {@link FileInputStream} for the specified file, providing better
     * error messages than simply calling <code>new FileInputStream(file)</code>.
     * <p>
     * At the end of the method either the stream will be successfully opened,
     * or an exception will have been thrown.
     * <p>
     * An exception is thrown if the file does not exist.
     * An exception is thrown if the file object exists but is a directory.
     * An exception is thrown if the file exists but cannot be read.
     * 
     * @param file  the file to open for input, must not be <code>null</code>
     * @return a new {@link FileInputStream} for the specified file
     * @throws FileNotFoundException if the file does not exist
     * @throws IOException if the file object is a directory
     * @throws IOException if the file cannot be read
     * @since Commons IO 1.3
     */
    public static FileInputStream openInputStream(File file) throws OTSException {
    	try {
	        if (file.exists()) {
	            if (file.isDirectory()) {
	                throw new IOException("File '" + file + "' exists but is a directory");
	            }
	            if (file.canRead() == false) {
	                throw new IOException("File '" + file + "' cannot be read");
	            }
	        } else {
	            throw new FileNotFoundException("File '" + file + "' does not exist");
	        }
	        return new FileInputStream(file);
    	}catch (Exception e) {
    		throw new OTSException(e);
    	}
    }
    
    /**
     * Reads the contents of a file into a String.
     * The file is always closed.
     *
     * @param file  the file to read, must not be <code>null</code>
     * @param encoding  the encoding to use, <code>null</code> means platform default
     * @return the file contents, never <code>null</code>
     * @throws OTSException in case of an I/O error
     */
    public static String readFileToString(File file, String encoding) throws OTSException {
        InputStream in = null;
        try {
            in = openInputStream(file);
            return IOUtils.toString(in, encoding);
        } catch(IOException e) {
        	throw new OTSException(e);
        } finally {
            IOUtils.closeQuietly(in);
        }
    }
    
	/**
	 * Writes a String to a file creating the file if it does not exist.
	 * There is no writeStringToFile method without encoding parameter because the default encoding can differ between platforms and will have inconsistent results.
	 * @Parameters file the file to write
	 * @data the content to write to the file
	 * @encoding the encoding to use, null means platform default
	 * @throws OTSException
	 */
	public static void writeStringToFile(File file, String data, String encoding) throws OTSException {
		OutputStream out = null;
		try {
			out = new FileOutputStream(file);
			IOUtils.write(data, out, encoding);
		} catch (IOException e) {
			throw new OTSException(e);
		} finally {
			IOUtils.closeQuietly(out);
		}
	}
	
	public static void main(String[] args) throws Exception {
		
	}
}
